package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.dto.DishDto;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RequestMapping("/dish")
@RestController
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

@PostMapping
    public R save(@RequestBody DishDto dishDto){
            log.info("新增菜品");
            log.info(dishDto.toString());
            dishService.saveWhitFlavor(dishDto);
            String key = "dish_"+dishDto.getCategoryId()+"_1";
            redisTemplate.delete(key);
        return R.success("新增成功");
    }

    /**
     * 实现分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public  R page(int page ,int pageSize,String name){
        Page<DishDto> dishDtoPage = dishService.pageByName(page, pageSize, name);
        return R.success(dishDtoPage);
    }
/**
 * 根据id查询菜品信息和对应的口味信息
 * @param id
 * @return
 */
@GetMapping("/{id}")
public R get (@PathVariable Long id){
    DishDto dishDto = dishService.gteByIdFlavor(id);
    return R.success(dishDto) ;
}


/**
 * 修改菜品
 * @param dishDto
 * @return
 */
@PutMapping
public  R update(@RequestBody DishDto dishDto){
    log.info(dishDto.toString());
    dishService.updateWhitFlavor(dishDto);
    String key = "dish_"+dishDto.getCategoryId()+"_1";
    //清理某个菜品下面的缓存
    redisTemplate.delete(key);
    return R.success("菜品修改成功");
}
//@GetMapping("/list")
//public R dishList(Dish dish){
//    LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
//    lqw.eq(dish.getCategoryId()!= null,Dish::getCategoryId,dish.getCategoryId());
//    lqw.eq(Dish::getStatus,1);
//    lqw.orderByDesc(Dish::getUpdateTime);
//    List<Dish> list = dishService.list(lqw);
//    return R.success(list);
//}
    /**
     * 根据条件查询对应得菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtos = null;
        //构造动态key
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        dishDtos   =(List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null){
            //如果存在，直接返回
            return R.success(dishDtos);
        }
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
    lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId,dish.getCategoryId());
    //菜品是否为停售或者起售状态
    lqw.eq(Dish::getStatus,1);
    //排序
    lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
    List<Dish> list = dishService.list(lqw);
    List<DishDto> dishdtoList = list.stream().map(itheima ->{
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(itheima,dishDto);//拷贝
        //获取菜品的id信息
        Long categoryId = itheima.getCategoryId();
        //根据id查询菜品信息
        Category category = categoryService.getById(categoryId);
        if(category != null){
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
        }
        //获取当前菜品的id
        Long id = itheima.getId();
        //SQL:select * from dish_flavor where dish_id = ?
        LambdaQueryWrapper<DishFlavor> flavorlqw = new LambdaQueryWrapper<>();
        flavorlqw.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(flavorlqw);
        dishDto.setFlavors(dishFlavors);
        return dishDto;

    }).collect(Collectors.toList());
    redisTemplate.opsForValue().set(key,dishDtos,5, TimeUnit.MINUTES);
    return R.success(dishdtoList);
}

    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping
public R delete(@RequestParam List<Long> ids){
        log.info("删除：{}",ids);
        dishService.removeWhitDish(ids);
        return  R.success("删除成功");
}

@PostMapping("/status/0")
public R status(@RequestParam List<Long> ids){
        log.info("停售：{}",ids);
    List<Dish> dishes = dishService.listByIds(ids);
    for (Dish dish : dishes) {
        dish.setStatus(0);
    }
    dishService.saveOrUpdateBatch(dishes);
    return R.success("修改成功");
    }

    @PostMapping("/status/1")
    public R status1(@RequestParam List<Long> ids){
        log.info("停售：{}",ids);
        List<Dish> dishes = dishService.listByIds(ids);
        for (Dish dish : dishes) {
            dish.setStatus(1);
        }
        dishService.saveOrUpdateBatch(dishes);
        return R.success("修改成功");
    }
}
